<script setup lang="ts">
import {
  apiEmpower,
  apiLogin,
  apiLoginByPhone,
  apiRegister,
  sendSms,
  h5Login,
  defaultSetting
} from "@/apis/login";
import cache from "@/utils/cache";
import { jump, router, toast } from "@/utils/tools";
import configObj from "@/config/index";
import { useUserStore } from "@/stores/user";
import { setToken, wxLogin } from "@/utils/auth";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { onLaunch } from "@dcloudio/uni-app";
//console.log(configObj);
const userids = ref("");
const userStore = useUserStore();
const tel = ref("11111111111");
let code = ref("");
let countdown = ref(0);
let uuid = ref("");
const checkValue = ref([])
const telReg = /^1[3-9]\d{9}$/;
const checkedqy = ref(false)
const agreement1 = ref(null)
const agreement5 = ref(null)
const handleH5login = async () => {
  // const redirect_uri = encodeURIComponent(window.location.href);
  // const appid = "wx4f7b3dfbe06b8f45";
  // const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  // // var obj = {
  // //   appid: appid, // 微信开放平台上申请的应用appid
  // //   redirect_uri: redirect_uri, // 授权回调页面
  // //   state: "STATE", // 可携带的参数，建议填写，用于防止CSRF攻击
  // //   scope: "snsapi_login", // 授权作用域，snsapi_login只能获取到openid和access_token等基本信息
  // //   self_redirect: "", // 授权后重定向的自定义回调页面，建议选填
  // //   style: "", // 按钮样式，支持black和white两种
  // //   href: "", // 自定义样式链接地址，如果设置则style参数失效
  // // };
  // // let fullUrl = "https://open.weixin.qq.com/connect/qrconnect?";
  // window.location.href = authUrl;
  if (!tel.value) {
    return toast("请输入手机号");
  }
  if (!telReg.test(tel.value)) {
    return toast("请输入正确手机号");
  }
  if (!code.value) {
    return toast("请输入验证码");
  }
  const data = {
    phonenumber: tel.value, //手机号
    code: code.value, //验证码
    uuid: uuid.value,
  };
  //console.log("data", data);
  let res: any = await h5Login(data);
  if (res.code == 200) {
    userStore.login(res.appUser);
    toast("登录成功");
    // uni.switchTab({
    //   url: "/pages/index/index",
    // });
    uni.navigateBack({ delta: 1 });
  } else {
    toast(res.msg);
  }
};

const sendCode = async () => {
  if (!tel.value) {
    return toast("请输入手机号");
  }
  if (!telReg.test(tel.value)) {
    return toast("请输入正确手机号");
  }
  if (countdown.value > 0) {
    return;
  }
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value -= 1;
    } else {
      clearInterval(timer);
    }
  }, 1000);

  let res: any = await sendSms({ phone: tel.value });
  if (res.code == 200) {
    uuid.value = res.data.uuid;
  }
};

const cancel = () => {
  //console.log("cancel----------");
  jump({
    url: "/pages/index/index",
    method: "switchTab",
  });
  // setTimeout(() => {
  //     toast('取消登录~');
  // }, 1000)
};
// #ifdef  MP-WEIXIN
const needAuthorization = ref(false);
const privacyContractName = ref("");
const privacyPopup = ref();
const isAgree = ref(false);
const handleLogin = async (e: any) => {
  if (!checkValue.value.length) {
    toast('请选择用户服务协议！');
    return
  }
  if (e.detail.errMsg == "getPhoneNumber:ok") {
    const code = e.detail.code;
    const res = await apiLoginByPhone({ code });
    if (res.code === 200) {
      const phonenumber = res.msg;
      uni.$uv.debounce(login(phonenumber), 1000);
    } else {
      toast(res.msg);
    }
  } else {
    toast("授权失败");
  }
  // uni.$uv.debounce(login(), 1000);
};

const login = async (phonenumber) => {
  setTimeout(async () => {
    let { code } = await wxLogin();
    const inviterId = uni.getStorageSync("inviterId");
    let commodityId = uni.getStorageSync("shareDetailId") ? uni.getStorageSync("shareDetailId") : '';
    let shareTitle = uni.getStorageSync("shareTitle") ? uni.getStorageSync("shareTitle") : ''
    if (shareTitle !== '推荐榜') {
      commodityId = ''
    }
    //console.log("uuuuuuu:" + inviterId);
    let res = await apiRegister({ code, phonenumber, inviterId, commodityId });

    if (res.code != 200) {
      toast(res.msg);
      return false;
    }
    userStore.login(res.data.appUser);
    toast("登录成功，即将跳转首页~");
    setTimeout(() => {
      router("/pages/index/index", "switchTab");
    }, 1500);
  }, 500);

};
// 同意隐私协议
const handleAgreePrivacyAuthorization = (e: any) => {
  //console.log("隐私协议---", e);
  isAgree.value = true;
  privacyPopup.value.close();
};
// 拒绝隐私协议
const handlePrivacyCancel = (e: any) => {
  privacyPopup.value.close();
};
const changeqy = (e: any) => {
  //console.log(e.detail.value)
  checkValue.value = e.detail.value
}
const getDefaultSetting = async () => {
  let res = await defaultSetting({});
  //console.log(res, '隐私协议')
  if (res.code === 200) {
    agreement1.value = res.data.agreement1
    agreement5.value = res.data.agreement5
  }
}
const vipChange = (type: any) => {
  // 1 用户手册 2 隐私协议
  let url: any = null;
  let links: any = null;
  if (type === 1) {
    // 用户服务协议
    links = agreement5.value;
    url = `/pages/login/agreement?title=用户手册&links=${links}`;
  } else if (type === 2) {
    //隐私政策
    links = agreement1.value;
    url = `/pages/login/agreement?title=隐私政策&links=${links}`;
  }


  switch (uni.getSystemInfoSync().platform) {
    case 'android':
      //console.log('安卓');
      // 这里直接调用原生的方法，我们上面定义的
      // #ifdef MP-WEIXIN

      uni.downloadFile({
        url: links,
        success: function (res) {
          var filePath = res.tempFilePath;
          uni.openDocument({
            filePath: filePath,
            showMenu: true,
            success: function (res) {
              //console.log('打开文档成功');
            }
          });
        }
      });
      // #endif
      break;
    case 'ios':
      //console.log('IOS');
      //这里跳转web-view页面
      uni.navigateTo({
        url: url
      });
      break;
    default:
      uni.navigateTo({
        url: url
      });
      break;
  }
}
onLaunch(() => {
  //console.log("冷启动=---");
});

// #endif
onLoad(() => {
  //console.log("第一次加载---");
  userids.value = uni.getStorageSync("inviterId");
  // #ifdef  MP-WEIXIN
  wx.getPrivacySetting({
    success(res: any) {
      //console.log("隐私协议", res);
      needAuthorization.value = res.needAuthorization;
      privacyContractName.value = res.privacyContractName;
      //console.log("隐私协议", needAuthorization, privacyContractName);
    },
  });
  // #endif
});
onShow(() => {
  getDefaultSetting()
})
</script>

<template>
  <view class="body-bg">
    <!-- #ifdef MP-WEIXIN -->
    <view class="flex container flex-column align-center">
      <view class="title flex align-center justify-around flex-column">
        <text class="text-xxxxl">欢迎使用</text>
        <text class="sub-title"> 奇石家小程序 </text>
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <view class="flex flex-column operation">
        <view class="login-btn flex flex-column justify-around">
          <button open-type="getPhoneNumber" @getphonenumber="handleLogin" class="btn1 text-df">
            手机号快捷登录
          </button>
          <button class="btn2 text-df" @click="cancel">取消登录</button>
        </view>
        <view class="check-xy">
          <view>
            <checkbox-group @change="changeqy">
              <label>
                <checkbox value="1" :checked="checkedqy" />
              </label>
            </checkbox-group>
          </view>
          <view class="flex protocol">
            <view>已阅读并同意</view>
            <view class="vipxy" @click="vipChange(1)">《用户服务协议》</view>
            <view>和</view>
            <view class="vipxy" @click="vipChange(2)">《隐私保护政策》</view>
          </view>
        </view>
      </view>
      <view> </view>
      <!-- #endif -->
      <!-- #ifdef WEB -->
      <view @click="handleH5login">h5登录</view>
      <!-- #endif -->
      <view> </view>
    </view>
    <!-- #endif -->

    <!-- #ifdef WEB -->
    <view class="flex container flex-column align-center">
      <view class="title flex align-center justify-around flex-column">
        <text class="text-xxxxl">欢迎使用</text>
        <text class="sub-title"> 奇石家小程序 </text>
      </view>
      <view class="login-btn flex flex-column justify-around">
        <view class="sss">
          <uv-input v-model="tel" type="number" :maxlength="11" placeholder="请输入手机号" border="none"> </uv-input>
        </view>
        <view class="sss">
          <uv-input v-model="code" type="number" :maxlength="6" placeholder="请输入验证码" border="none"> </uv-input>
          <text class="t-test" @click="sendCode">{{
            countdown > 0 ? `${countdown}秒后重新发送` : "发送验证码"
            }}</text>
        </view>
        <view class="h5-login" @click="handleH5login">登录</view>
      </view>
      <view> </view>
    </view>
    <!-- #endif -->

    <!-- #ifdef MP-WEIXIN -->
    <uv-popup ref="privacyPopup" @change="change" round="12">
      <view class="flex flex-column align-center privacy-box">
        <view class="tips margin-bottom-sm text-lg">
          <text>隐私保护提示</text>
        </view>
        <view class="text-df content margin-bottom">
          为了更好地保障您的权益，在您使用群相册服务小程序提供的服务前，请仔细阅读<text
            class="colorb">《乐石小程序隐私政策》</text>，并确认了解我们的服务内容。我们将在条款说明的范围内收集、使用你的个人信息。如果你不同意，我们将不能继续为你提供服务。

          <view>
            <text>若你点击“同意并继续”按钮，表示你已理解并同意以上协议全部内容。</text>
          </view>
        </view>
        <view class="flex flex-column btn-group justify-around text-df">
          <button class="btn-agree" open-type="agreePrivacyAuthorization"
            @agreeprivacyauthorization="handleAgreePrivacyAuthorization">
            同意并继续
          </button>
          <button class="btn-reject" @click="handlePrivacyCancel">取消</button>
        </view>
      </view>
    </uv-popup>
    <!-- #endif -->
  </view>
</template>

<style lang="scss" scoped>
page {
  background: url("https://www.stoneplayer.com/background/homePage.jpg") no-repeat;
  background-size: 100% 100%;
}

.container {
  display: flex;
  align-content: flex-end;
  justify-content: space-around;
  height: 100vh;
  background: url("https://www.stoneplayer.com/background/homePage.jpg") no-repeat;
  background-size: 100% 100%;
}

.title {
  color: #ffffff;
  height: 200rpx;
  font-weight: 700;

  text {
    text-shadow: 0 2px 2px rgba(0, 0, 0, 0.5);
  }
}

.text-xxl {
  font-weight: bold;
}

.login-btn {
  width: 600rpx;
  height: 300rpx;

  .btn1 {
    height: 100rpx;
    color: #bf0103;
    border-radius: 25px;
    background-color: rgba(255, 255, 255, 1);
  }

  .btn2 {
    height: 100rpx;
    border-radius: 25px;
    background-color: rgba(255, 255, 255, 0.25);
    border: 1px solid rgba(255, 255, 255, 1);
  }
}

.privacy-box {
  padding: 60rpx;

  .tips {
    font-weight: 700;
  }

  .content {
    color: #101010;
    text-indent: 2em;

    .colorb {
      color: #ff5504;
    }
  }
}

.btn-group {
  height: 250rpx;
  width: 100%;

  .btn-agree {
    height: 100rpx;
    background: #ff5402;
    border-radius: 25px;
    width: 100%;
    color: #ffffff;
  }

  .btn-reject {
    height: 100rpx;
    background: #ffffff;
    border-radius: 25px;
    width: 100%;
    border: 1px solid #4f4f4f;
  }
}

.sss {
  box-shadow: 1px 1px 4px 0px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin-top: 10rpx;
  width: 100%;
  // height: 100%;
  padding: 20rpx;
  font-size: 28rpx;
  color: #101010;
  // font-weight: bold;
  background: #ffffff;
  border-radius: 20rpx;
  position: relative;

  .t-test {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    // color: #efbb22;
  }
}

// ::v-deep .uni-input-wrapper,
// .uni-input-form {
//   background: red;
// }

.h5-login {
  height: 80rpx;
  color: #bf0103;
  border-radius: 25px;
  background-color: rgba(255, 255, 255, 1);
  text-align: center;
  line-height: 80rpx;
  margin-top: 10rpx;
  font-weight: 500;
}

.operation {
  width: 600rpx;
  align-items: center;
}

.check-xy {
  width: 600rpx;
  box-sizing: border-box;
  margin: 30rpx 10rpx;
  display: flex;
  // align-items: center;
  color: #fff;
}

.protocol {
  flex-wrap: wrap;
}

.vipxy {
  font-weight: bold;
  margin-left: 10rpx;
  color: #000;
}

::v-deep .wx-checkbox-input.wx-checkbox-input-checked {
  background-color: #C7452F !important;
  border-color: #C7452F !important;
  color: #ffffff !important;
}

::v-deep .uni-checkbox-input.uni-checkbox-input-checked {
  background-color: #C7452F !important;
  border-color: #C7452F !important;
  color: #ffffff !important;
}

/* #ifdef H5 */
::v-deep uni-checkbox .uni-checkbox-input {
  border-radius: 50%;
  width: 36rpx;
  height: 36rpx;
  border: 1rpx solid #cccccc;
}

/* #endif */
/* 微信样式 */
/* #ifdef APP-PLUS ||MP-WEIXIN */

::v-deep checkbox .wx-checkbox-input {
  border-radius: 50%;
  width: 36rpx;
  height: 36rpx;
  border: 1rpx solid #cccccc;
}

::v-deep .wx-checkbox-input .wx-checkbox-input-checked {
  border: none !important;
}

/* #endif */
</style>
